const vscode = require('vscode');
const path = require('path');
const hiSmartLiteEx = require('../../hiSmartLiteEx');
const LoginClass = require('./loginClass');
const fsUtil = require('../../util/fsUtil');

const createLoginPanelWbview = {
  async createPanel() {
    if (!this.myPanel !== undefined) {
      try {
        this.myPanel.reveal(vscode.ViewColumn.Active);
        await this.initWebviewPanel(this.myPanel);
        const obj = new LoginClass(this.myPanel.webview);
        obj.getIsGiteeLogin();
        return;
      } catch (error) {
        vscode.window.showErrorMessage(error);
      }
    }

    this.myPanel = vscode.window.createWebviewPanel(
      'giteeLogin',
      '登录',
      vscode.ViewColumn.One,
      {
        enableScripts: true,
        retainContextWhenHidden: true
      }
    );
    this.myPanel.iconPath = vscode.Uri.file(path.join(hiSmartLiteEx.extensionPath, 'media/images/foundation.svg'));
    // 初始化面板
    await this.initWebviewPanel(this.myPanel);
    hiSmartLiteEx.loginpanel = this.myPanel;
    this.myPanel.onDidDispose(() => {
      this.myPanel.dispose();
      hiSmartLiteEx.myPanel = null;
    }, null, hiSmartLiteEx.context.subscriptions);

    this.myPanel.webview.onDidReceiveMessage(message => {
      const obj = new LoginClass(this.myPanel.webview);
      switch (message.command) {
        case 'isGiteeLogin':
          obj.getIsGiteeLogin();
          break;
        case 'handleLogin':
          obj.handleLogin(message);
          break;
        case 'cancelLogin':
          obj.cancelLogin();
          break;
        default:
          break;
      }
    }, null, hiSmartLiteEx.context.subscriptions);
  },

  async initWebviewPanel(myPanel) {
    const htmlpath = vscode.Uri.file(path.join(hiSmartLiteEx.extensionPath, 'media/pages/setting/giteeLogin.html'));
    let html = ((await vscode.workspace.openTextDocument(htmlpath)).getText().replace(/{{root}}/g,
      myPanel.webview.asWebviewUri(vscode.Uri.file(path.join(hiSmartLiteEx.extensionPath)))
    ));
    const toolkitUri = fsUtil.getUri(this.myPanel.webview, hiSmartLiteEx.context.extensionUri, ['node_modules', '@vscode', 'webview-ui-toolkit', 'dist', 'toolkit.js']);
    const iconCssUri = fsUtil.getUri(this.myPanel.webview, hiSmartLiteEx.context.extensionUri, ['node_modules', '@vscode', 'codicons', 'dist', 'codicon.css']);
    html = html.replace(/{{iconCssUri}}/g, iconCssUri.toString());
    myPanel.webview.html = html.replace(/{{toolkitUri}}/g, toolkitUri.toString());
  }
};

module.exports = createLoginPanelWbview;